const koa = require("koa");
/*if(!koa){
    console.log("hehe");
}*/
const app = new koa();
const convert = require('koa-convert');

// 全局处理工具
const app_config = require("./app_config.conf");
require("../tools/_include.t");
require("../tools/_Array.t");

// session
const session = require("koa-session");
app.keys = ['keys', 'keykeys'];
app.use(convert(session(app)));

// 日志文件管理
const log4js = require('koa-log4');
app_config.is_dev ? true : log4js.configure("server/log4js.json");
app.use(log4js.koaLogger(log4js.getLogger('app'), {
    level: 'auto'
}));

// co
global.co = require("co");

const qx = require("koa-qx-router");
const qxClient = new qx.client({
    port: 1333,
    hostname: "127.0.0.1",
    auth: {
        name: "fangchebbs",
        pass: "fangchebbs"
    }
});

app.use(qxClient.cors({
    //origin: ["chrome-extension", "dotnar.com", "fangchepingtai.com", "127.0.0.1", "loaclhost:", "*"]
    origin: ["chrome-extension",'120.25.254.241', "dotnar.com", "fangchepingtai.com", "127.0.0.1", "loaclhost:", "*","bbs.fangchepingtai.com"]
}));

app.use(co.wrap(function *(ctx,next) {
    console.log("hehe")

    yield next()
}))

app.use(qxClient.auth());
app.use(qxClient.bodyParser());

// qiniu
require("../tools/qiniu.t");

// bmob
global.bmob = require("../tools/Bmob.t");

// mongodb
const MongoClient = require('mongodb').MongoClient;
global.ObjectID = require('mongodb').ObjectID;

co(function*() {
    global.mongo = require("../tools/mongo.t");
    global.db = yield MongoClient.connect('mongodb://127.0.0.1:27017/fangchebbs');
    const router = yield require("../complex/complex");

    router.apis.push({
        name: "getAllApis",
        content: "获取所有接口描述",
        apiroot: "/allApis"
    });
    router.router.get("/allApis", function*() {
        this.body = router.apis;
    });
    router.router.post("/qiniucallback", function*() {
        console.log(this.request.body);
        this.body = {
            stastus: "ok"
        };
    });

    console.log("api:", "/qiniucallback")
    app.use(convert(router.router.routes()));
    app.use(convert(router.router.allowedMethods()));

    app.listen(1334, qxClient.registerServer(app));
    console.log(("server start at 1334," + new Date().toLocaleString()).data);
}).catch(e => {
    console.log("start err:", e);
    console.log(new Date().toLocaleString());
});